import { check } from 'meteor/check';
import { ChannelMembers, isMember } from '/imports/models/ChannelMembers';
import { Notifications } from '/imports/models/Notifications';

Meteor.methods({
  // 用户申请加入频道
  // options._id
  // options.channelId
  // options.policy
  // options.owner
  joinChannel(options) {
    let policy = options.policy;
    
    // 私密频道并且不允许申请
    if (policy.name == 'private' && !policy.apply) {
      return false;
    }

    // 公开频道并且直接加入
    if (policy.name == 'public' && !policy.apply) {
      if (!isMember(options._id, Meteor.userId())) {
        ChannelMembers.insert({
          channel_id: options._id,
          user_id: Meteor.userId()
        });
        return 'join_success';
      }
    }

    // 需要申请
    if ((policy.name == 'public' && policy.apply) || (policy.name == 'private' && policy.apply)) {
      // 发送[申请加入]通知
      Notifications.insert({
        type: 'UserJoinChannel',
        user_id: options.owner.id, // 通知接收者
        details: {
          _id: options._id,
          channelId: options.channelId,
          user_id: Meteor.userId(),
          username: Meteor.user().username,
          avatar: Meteor.user().profile.avatar,
          text: '申请加入你的频道'
          // 用户[username]申请加入你的频道[频道ID]
        }
      });
      return 'need_allow';
    }
  },
  // 频道管理员同意后
  // 允许用户加入频道
  confirmJoin(options) {
    check(options._id, String);
    check(options.user_id, String);
    check(options.channelId, String);
    check(options.notification_id, String);
    
    ChannelMembers.insert({
      channel_id: options._id,
      user_id: options.user_id
    });
    
    Notifications.insert({
      type: 'UserJoinChannelSuccess',
      user_id: options.user_id,
      details: {
        _id: options._id,
        channelId: options.channelId,
        text: '你已成功加入频道'
        // 你已成功加入频道[频道ID]
      }
    });

    return Notifications.remove({_id: options.notification_id});
  },
  deleteJoin(options) {
    check(options._id, String);
    return Notifications.remove({_id: options._id});
  }
});